#!/bin/bash
set -e

# ANSI formatting
BOLD='\033[1m'
RESET='\033[0m'

echo "=== Terraform Backend Configuration Setup ==="
echo ""

# Prompt for terraform directory
echo "Available Terraform configurations:"
echo "1. terraform-ecs-ec2 (EC2 launch type)"
echo "2. terraform-ecs-fargate (Fargate launch type)"
echo "3. terraform-ecs-ec2-sqs (⚠️  Special deployment with SQS - not for widespread use)"
echo ""
read -p "Select terraform directory (1, 2, or 3): " dir_choice

case $dir_choice in
    1)
        TERRAFORM_DIR="terraform-ecs-ec2"
        ;;
    2)
        TERRAFORM_DIR="terraform-ecs-fargate"
        ;;
    3)
        TERRAFORM_DIR="terraform-ecs-ec2-sqs"
        echo "⚠️  You selected the specialized SQS deployment. This should only be used for specific use cases."
        ;;
    *)
        echo "❌ Invalid selection. Please choose 1, 2, or 3."
        exit 1
        ;;
esac

echo "Selected: $TERRAFORM_DIR"
echo ""

# Check if backend files already exist
if [[ -f "$TERRAFORM_DIR/infra/backend.tfbackend" ]] || [[ -f "$TERRAFORM_DIR/app/backend.tfbackend" ]]; then
    echo "⚠️  backend.tfbackend files already exist!"
    read -p "Do you want to overwrite them? (y/N): " overwrite
    if [[ "$overwrite" != "y" && "$overwrite" != "Y" ]]; then
        echo "Aborted."
        exit 1
    fi
fi

echo "Setting up S3 backend configuration for both infra and app..."
echo ""

# Collect user input
read -p "Enter your S3 bucket name for Terraform state: " bucket
read -p "Enter your AWS region (default: us-east-1): " region
region=${region:-us-east-1}

# Create infra backend config
echo "Creating infra backend config..."
cat > $TERRAFORM_DIR/infra/backend.tfbackend << EOF
# S3 Backend Configuration - Infrastructure
# Generated by './init-terraform.sh'

bucket = "$bucket"
key    = "infra/terraform.tfstate"
region = "$region"
encrypt = true

EOF

# Create app backend config
echo "Creating app backend config..."
cat > $TERRAFORM_DIR/app/backend.tfbackend << EOF
# S3 Backend Configuration - Application
# Generated by './init-terraform.sh'

bucket = "$bucket"
key    = "app/terraform.tfstate"
region = "$region"
encrypt = true

EOF

# Create app remote state config
echo "Creating app remote state config..."
cat > $TERRAFORM_DIR/app/remote-state.auto.tfvars << EOF
# Auto-generated remote state configuration for app/
# Generated by './init-terraform.sh' from infra/backend.tfbackend

infra_state_bucket = "$bucket"
infra_state_region = "$region"

EOF

echo ""
echo "✅ Backend configurations created:"
echo "   - $TERRAFORM_DIR/infra/backend.tfbackend (key: infra/terraform.tfstate)"
echo "   - $TERRAFORM_DIR/app/backend.tfbackend (key: app/terraform.tfstate)"
echo "   - $TERRAFORM_DIR/app/remote-state.auto.tfvars (infra state reference)"
echo ""


# Offer to create S3 bucket
read -p "Do you want me to create the S3 bucket if it doesn't exist? (Y/n): " create_bucket
create_bucket=${create_bucket:-Y}

if [[ "$create_bucket" = "Y" || "$create_bucket" = "y" || "$create_bucket" = "" ]]; then
    echo ""
    echo "🪣 Creating S3 bucket if it doesn't exist..."

    if aws s3 ls "s3://$bucket" >/dev/null 2>&1; then
        echo "✅ Bucket $bucket already exists"
    else
        echo "Creating bucket: $bucket in region: $region"
        if aws s3 mb "s3://$bucket" --region "$region"; then
            echo "✅ Bucket $bucket created successfully"
        else
            echo "❌ Failed to create bucket. Please create it manually or check your AWS credentials"
        fi
    fi
fi

echo ""
echo "Note: Make sure you have proper AWS credentials configured!"
echo ""
echo "➡️  Next steps:"
echo ""
echo -e "${BOLD}Setup the core infrastructure${RESET}"
echo ""
echo "1. cd $TERRAFORM_DIR/infra"
echo "2. terraform init -backend-config=backend.tfbackend"
echo "3. terraform apply"
echo ""
echo -e "Once the infrastructure is setup, ${BOLD}setup the application${RESET}:"
echo ""
echo "1. cd $TERRAFORM_DIR/app"
echo "2. terraform init -backend-config=backend.tfbackend"
echo "3. terraform apply"
echo ""
echo "When the \`terraform apply\` finishes for \`app\`, Sequin should be running and available at the hostname output by Terraform."
